<template>
  <div class="header">
    <div class="left">
      <div class="data" @click="toDataDashboards" v-show="route.path.includes('home')">
        <el-icon class="icon">
          <Histogram />
        </el-icon>
        <span>数据仪表盘</span>
      </div>
      <div class="data" @click="toHome" v-show="!route.path.includes('home')">
        <el-icon class="icon">
          <HomeFilled />
        </el-icon>
        <span>首页</span>
      </div>

      <!-- <div class="data" @click="toHome">
        <el-icon class="icon"><HomeFilled /></el-icon>
        <span>首页</span>
      </div>
      <div class="data" @click="toDataDashboards">
        <el-icon class="icon"><Histogram /></el-icon>
        <span>数据仪表盘</span>
      </div> -->

      <div class="avatar">
        <img v-if="info.AvatorUrl" :src="info.AvatorUrl" alt="" @error="setDefaultImage" />
      </div>
      <div class="info">
        <span class="name">{{ info.Name }} <span class="copy" @click="onCopy(info.UserID)">({{info.UserID}})</span > </span>
        <span class="corp">{{ info.CorpShortName }} <span  class="copy" @click="onCopy(info.CorpID)">({{info.CorpID}})</span></span>
      </div>
    </div>
    <div class="right">
      <span v-if="!!info.ExpTime" class="right-span">{{`账号有效期：${info.ExpTime}`}}</span>
      <span class="right-span right-btn" @click="onSync">同步企微数据</span>
      <span class="right-span right-btn" @click="identifyNewAccount">识别新账号</span>
      <span class="right-span right-btn" @click="logout_">退出</span>
    </div>
  </div>
  <div class="title">
    <div>{{ route.meta.title }}</div>
    <div v-if="route.meta.title == '首页'" @click="handlerSetting" class="title-right">
      <el-icon><Setting /></el-icon><span>高级设置</span>
    </div>
  </div>

  <ZWDialog
    title="识别新账号"
    :width="960"
    :visible="visible"
    :isRenderFooter="false"
    :cancel="cancelDialog"
  >
    <div class="account-dialog">
      <!-- <div class="dialog-title">识别到的新账号：</div> -->
      <AccountList ref="accountListRef" v-model="selectAccountId" @submit="getSelectUserInfo" />
      <div class="btns">
        <div class="left">
          <el-button :loading="addAccountLoading" @click="addAccountFn">添加账号</el-button>
        </div>
        <div class="right">
          <!-- <el-button @click="reset">重新识别</el-button> -->
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </div>
    </div>
  </ZWDialog>

  <el-dialog v-model="dialogTableVisible" :title="dialogTitle" @close="closeDialog">
    <div class="dialog-box">
      <img :src="qrCode" alt="" />
    </div>
  </el-dialog>

  <el-dialog v-model="dialogAccountVisible" width="680px" title="个人信息" @close="closeDialogAccount">
    <div class="dialog-user-box" v-if="corpLogo || avatorUrl || nickName">
     <div>
        <img class="corp-logo-img" v-if="corpLogo" :src="corpLogo" alt="" />
      </div>
      <div>
        <img class="avator-img" v-if="avatorUrl" :src="avatorUrl" alt="" />
      </div>
      <div class="nick-name" v-if="nickName">
        <span>{{nickName}}</span>
      </div>
    </div>
    <div v-if="isAuthCode" class="authcode">
        <span>验证码:</span>
        <el-input v-model.trim="authCode" :maxlength="6" :minlength="6" placeholder="请输入6位数字的验证码" @keydown.enter="submitAuthCode" />
        <el-button type="primary" @click="submitAuthCode" >确定</el-button>
    </div>
  </el-dialog>

  <Setting ref="settingRef" />

  <el-dialog v-model="dialogSync" width="30%" title="提示">
    <div class="dialog-sync-text">
      该账号未同步企微数据，是否立即同步
    </div>
    <template #footer>
      <el-button @click="dialogSyncFn('2')">取 消</el-button>
      <el-button type="primary" @click="dialogSyncFn('1')">同 步</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useClipboard3 from 'vue-clipboard3';
import { computed, reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading  } from 'element-plus'
import { useStore } from '../../store/index'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { getUserInfo, logout, getSystemSync } from '../../ajax/api/common'
import QrcodeVue from 'qrcode.vue'
import {addAccount} from '../../ajax/api/login'
import { useSignalR } from '@renderer/utils/ws'
import ZWDialog from '../ZWDialog.vue'
import AccountList from '../../view/common/components/AccountList.vue'
import useAddAccount from '../../hooks/addAccountSocket'
import Setting from './Setting.vue'
import { log } from 'console';

const store = useStore()
const route = useRoute()
const router = useRouter()
const accountListRef = ref<any>(null)
let selectAccountId = ref<string>('')
let visible = ref<boolean>(false)
let qrSize = ref<number>(300)
const settingRef = ref<any>(null)
const dialogSync = ref<any>(false)
const selectUserInfo = ref<any>({})

  let {
  addAccountFn,
  closeDialog,
  closeDialogAccount,
  qrCode,
  dialogTitle,
  addAccountLoading,
  dialogTableVisible,
  dialogAccountVisible,
  userInfo,
  corpLogo,
  avatorUrl,
  nickName,
  authCode,
  isAuthCode,
  submitAuthCode
} = useAddAccount((flag:boolean)=>{
  if(flag){
    reset()
  }
})

let signalr: any = ''
let signalrSync: any = ''
let loading:any = null

const startWorkUser = (val) => {
  signalr.invoke('WorkuserInit', {
    userList: [val]
  })
  signalr.on('workuserState', (data) => {
    if(data.type === 2) {
      store.commit('common/USERID', '')
      router.push({path: '/login'})
    }
  })
}

type stateType = {
  Name: string
  CorpShortName: string
  AvatorUrl: string,
  ExpTime: string,
  UserID: string,
  CorpID: string,
}
const info = reactive<stateType>({
  Name: '--',
  CorpShortName: '--',
  AvatorUrl: '',
  ExpTime: '--',
  UserID:'--',
  CorpID:'--',
})

const setDefaultImage = (e: any) => {
  e.target.src = new URL('../../assets/img/user.png', import.meta.url).href
}

const toDataDashboards = () => {
  router.push({ path: '/dataDashboards' })
}

const toHome = () => {
  router.push({ path: '/home' })
}
const { toClipboard } = useClipboard3()
const onCopy = (v:any) => {
  try {
    toClipboard(v)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}
const logout_ = () => {
  ElMessageBox.confirm('确定退出吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // logout()
    store.dispatch('common/logout')
    router.push({path: '/login'})
  })
}
// 同步企微数据
const onSync = async () => {
  // await getSystemSync()
  // ElMessage.success('同步成功')
  syncFn(true)
}

const identifyNewAccount = () => {
  selectAccountId.value = store.state.common.userId
  visible.value = true
}

const cancelDialog = () => {
  visible.value = false
}

const reset = () => {
  visible.value = true
  selectAccountId.value = ''
  // store.commit('common/USERID', '')
  accountListRef.value.init()
}

const getSelectUserInfo = (val) => {
  console.log(val,'valvalval')
  selectUserInfo.value = {...val}
}

const dialogSyncFn = async (type: string) => {
  store.commit('common/USERID', selectAccountId.value)
  initUserInfo()
  dialogSync.value = false
  if(type == '1') { 
    store.commit('common/SETISSYNC', true)
    syncFn()
    // await getSystemSync()
  }
}

const save = () => {
  if(!!selectAccountId.value){
    visible.value = false
    signalr = useSignalR({
      url: 'ws/aggregate-chat/workuser',
      onStart() {
        startWorkUser(selectAccountId.value)
      }
    })
    if(!selectUserInfo.value.hasSyncExternalDataByAfterLogined) {
      dialogSync.value = true
    }else {
      store.commit('common/USERID', selectAccountId.value)
      initUserInfo()
    }

    // 点击保存到首页
    router.replace('/home');
    ElMessage.success('账号切换成功～')
  }else{
    ElMessage.warning('请选择账号')
  }
}

const handlerSetting = () => {
  settingRef.value.dialogTable.visible = true
}

const initUserInfo = async () => {
  const res: any = await getUserInfo()
  if (!!res) {
    info.AvatorUrl = res.Avatar || ''
    info.Name = res.Name || res.RealName || ''
    info.CorpShortName = res.CorpFullName || res.CorpShortName
    info.ExpTime = res.exp_time || '--'
    info.UserID = res.UserId || '--'
    info.CorpID = res.CorpId || '--'
    store.commit('common/USERINFO',info)
  }
  if(!res || res && !res.UserId) {
    store.dispatch('common/logout')
    router.push({path: '/login'})
  }
}

const startSync = async () => {
  let id = store.state.common.userId
  signalrSync.invoke('addressbookInit', {
    UserId: id
  })
  signalrSync.on('syncContactEvent', (data) => {
    console.log(data,'route.query12')
    if(data.type == 1 && data.status == 2) {
      loading.close()
      ElMessage.success('同步成功')
    }
  })
  await getSystemSync()

}


const syncFn = (type?: any) => {
  const isSync = store.getters['common/getIsSync']
  console.log(isSync,'route.query123')
  if(type || isSync) {
    store.commit('common/SETISSYNC', null)
    loading = ElLoading.service({
      lock: true,
      text: '数据同步....',
      background: 'rgba(0, 0, 0, 0.7)',
      customClass: 'zw-loading-global'
    })
    signalrSync = useSignalR({
      url: 'ws/aggregate-chat/addressbook',
      onStart() {
        startSync()
      }
    })
  }else {
    loading && loading.close()
  }
  
}


onMounted(async (): Promise<void> => {
  initUserInfo()
  syncFn()
})
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #0433ff;
  color: #fff;
  padding: 0 10px;
  box-sizing: border-box;

  .left {
    display: flex;
    align-items: center;

    .data {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 4px;
      border-radius: 6px;
      width: 80px;

      &:hover {
        cursor: pointer;
        background-color: #294ff5;
      }

      .icon {
        font-size: 28px;
      }

      span {
        font-size: 12px;
        line-height: 2;
      }
    }

    .avatar {
      width: 48px;
      height: 48px;
      border-radius: 8px;
      background-color: #f9f9f9;
      overflow: hidden;
      margin: 14px;

      img {
        width: 100%;
        height: 100%;
      }
    }
    .copy{
      color: #fff;
      font-size: 12px;
      margin-left: 4px;
      &:hover{
        background: #294ff5;
        cursor: pointer;
      }
    }

    .info {
      display: flex;
      flex-direction: column;
      font-size: 13px;

      span {
        line-height: 1;
      }

      .name {
        margin-bottom: 8px;
      }

      .corp {}
    }
  }

  .right {
    .right-span {
      margin-right: 16px;
      padding: 6px 10px;
      border-radius: 4px;
    }

    .right-btn {
      border: 1px solid #294ff5;

      &:hover {
        cursor: pointer;
        color: #eee;
        background-color: #294ff5;
      }
    }
  }
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  padding-left: 20px;
  box-shadow: 0 20px 20px #eee;
  font-size: 14px;
  letter-spacing: 1px;
  color: #555;
  font-weight: 600;
  letter-spacing: 1px;
  .title-right {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    color: #0433ff;
    span {
      padding-left: 6px;
    }
  }
}

.account-dialog{

  .dialog-title{

  }
  .btns{
      height: 60px;
      // flex: 1;
      // background-color: navy;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left{

      }
      .right{

      }
    }
}

.el-dialog{
  .el-dialog__body{
    // padding-bottom: 20px;
    .dialog-box{
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      img{
        width: 300px;
        height: 300px;
      }
    }
    .authcode {
        display: flex;
        align-items: center;
        justify-content: space-between;        
        padding: 0 120px;
        gap: 20px;
        .el-input {
            flex: 1;
        }
    }
  }
  .dialog-user-box{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .corp-logo-img {
      height: 60px;
    }
    .avator-img{
      margin-top: 20px;
      width: 60px;
      height: 60px;
      border-radius: 12px;
      // margin-right: 20px;
    }
    .nick-name {
      margin-top: 20px;
      text-align: center;
    }
    span{
      color: #666;
    }
    
  }
}


</style>
